import { VuexModule, Module, Action, Mutation, getModule } from 'vuex-module-decorators'
import store from '@/store'
import {RouteRecordRaw} from 'vue-router'
import {asyncRoutes} from '@/router'

const hasPermission = (roleLevel:number, route: RouteRecordRaw) => {
    if (route.meta && route.meta.roleLevels) {
        const routeRoleLevels:any = route.meta.roleLevels;
        if(routeRoleLevels.indexOf(roleLevel) != -1){
            return true;
        }
        return false;
    } else {
      return true
    }
  }

export const filterAsyncRoutes = (routes: RouteRecordRaw[], roleLevel:number) => {
    const res: RouteRecordRaw[] = []
    routes.forEach(route => {
      const r = { ...route }
      if (hasPermission(roleLevel, r)) {
        if (r.children) {
          r.children = filterAsyncRoutes(r.children, roleLevel)
        }
        res.push(r)
      }
      console.log("res",res);
      
    })
    return res
}

export interface IPermissionState {
  dynamicRoutes: RouteRecordRaw[],
  addRouteState:boolean;
}

@Module({ dynamic: true, store, name: 'permission' })
class Permission extends VuexModule implements IPermissionState {
  public dynamicRoutes: RouteRecordRaw[] = []
  public addRouteState:boolean = false;

  @Mutation
  private SET_ROUTES(routes: RouteRecordRaw[]) {
    this.dynamicRoutes = routes
  }

  @Mutation
  private SET_ADDROUTESSTATE(addState: boolean) {
    this.addRouteState = addState
  }

  @Action
  public GenerateRoutes(roleLevel: number) {
    let accessedRoutes
    accessedRoutes = filterAsyncRoutes(asyncRoutes, roleLevel)
    this.SET_ROUTES(accessedRoutes)
  }

  @Action
  public SetAddRoutesState(stateValue: boolean) {
    this.SET_ADDROUTESSTATE(stateValue)
  }
}

export const PermissionModule = getModule(Permission)